<script setup lang="ts">
import { onMounted, computed, ref, reactive, onUnmounted } from 'vue'
import VuePlayer from '@/components/player/VuePlayer.vue'
import { useAlarmDataApi, useGetWaybillList, useWaybillApi } from '@/api/biz/waybill'
import moment from 'moment'
import { avControl, avRequest, queryHistory, historyAvRequest0, historyAvRequest, historyAvControl } from '@/api/gps/jt808/jt1078'
import FreightTimeCount from '@/views/biz/waybill/freightTimeCount.vue'
import { useDeviceAndStatusApi } from '@/api/gps/device'
import { computeSubTitle, jt1078AvsetAnalysis } from '@/utils/gps/format'
import MaOrgSelect from '@/components/ma-org/ma-org-select/index.vue'
import MaDictLabel from '@/components/ma-dict/ma-dict-label/index.vue'
import { useUserStore } from '@/store/modules/user'
import { useRoute } from 'vue-router'
import MaDictColumn from "@/components/ma-dict/ma-dict-column/index.vue";
import CdlMap from "@/components/map";
import Trajectory from "@/components/map-trajectory/trajectory";
import {useGetTrackPosApi} from "@/api/gps/gps";
const route = useRoute()

const dataInfo = ref<any>()
const trackRef = ref()
const trajectoryRef = ref()
const realTimeVideoRefs = ref<any[]>([])
const playbackVideoRef = ref()
const activeName = ref('first')
const alarmData = ref([])
const freightRef = ref()
const deviceInfo = ref()
const userStore = useUserStore()
const queryForm = reactive({
  deptId: userStore.user.orgId || 1,
  page: 1,
  limit: 1000
})
const waybillList = ref()
const currenWaybill = ref(0)
const loading = ref(false)
const isReplay = ref(false)

const trajectoryModel = ref()
const trackModel = ref()

init()
function init() {
  getWaybillList()
}

function initData(sysOrgId, id) {
  queryForm.deptId = parseInt(sysOrgId)
  currenWaybill.value = parseInt(id)
  getWaybill()
}
onMounted(() => {
  if (route.query.sysOrgId) {
    initData(route.query.sysOrgId, route.query.id)
  }
})

onUnmounted(() => {
  handleClose()
})
/**
 * 获取运单列表
 */
function getWaybillList() {
  useGetWaybillList(queryForm).then((res) => {
    waybillList.value = res.data.list
  })
}

/**
 * 选中运单的回调事件
 */
function waybillChange() {
  getWaybill()
}

/**
 * 获取运单信息
 */
function getWaybill() {
  loading.value = true
  useWaybillApi(currenWaybill.value).then((res) => {
    dataInfo.value = res.data
    const {imei, startTime, endTime, mineId, status} = dataInfo.value
    if (status) {
      if (status < 6) {
        isReplay.value = true
        playerRealVideo(imei)
      } else {
        isReplay.value = false
        playerHisVideo(imei, startTime,endTime)
      }
    }
    getAlarm(imei, startTime, endTime)
    obtainHistoricalTrajectory(imei, startTime, moment().format('YYYY-MM-DD HH:mm:ss'), mineId)
    loading.value = false
  })
}

function getAlarm(imei: string, startTime: string, endTime: string) {
  useAlarmDataApi({
    page: 1,
    size: 100,
    imei,
    startTime,
    endTime
  }).then((res) => {
    alarmData.value = res.data.list
  })
}

/**
 * 播放实时视频
 */
function playerRealVideo(imei: string) {
  useDeviceAndStatusApi(imei).then((res) => {
    deviceInfo.value = res.data
    const channelNames = jt1078AvsetAnalysis(res.data?.jt1078Avch, res.data?.jt1078Avset)
    if (channelNames.length === 0) {
      return
    }
    for (let i = 0; i < channelNames.length; i++) {
      let cl = channelNames[i]
      realTimeVideoRefs.value[i].init(({ play, fail, config }) => {
        avRequest({
          imei: dataInfo.value.imei,
          channel: cl.channel,
          streamType: 1,
          mediaType: 0}, config)
          .then((res) => {
            play(res.data.streamUrl, res.data.heartKey)
          })
          .catch(() => {
            fail()
          })
      }, true)
    }
  })
}

/**
 * 回放
 * @param imei
 * @param startTime
 * @param endTime
 */
function playerHisVideo(imei: string, startTime: string, endTime: string) {
  useDeviceAndStatusApi(imei).then((res) => {
    deviceInfo.value = res.data
    const channelNames = jt1078AvsetAnalysis(res.data?.jt1078Avch, res.data?.jt1078Avset)
    if (channelNames.length === 0) {
      return
    }
    for (let i = 0; i < channelNames.length; i++) {
      let cl = channelNames[i]
      realTimeVideoRefs.value[i].init(({ play, fail }) => {
        historyAvRequest0(dataInfo.value.imei, cl.channel, startTime, endTime)
          .then((res) => {
            play(res.data.historyUrl2, res.data.heartKey)
          })
          .catch(() => {
            fail()
          })
      })
    }
  })
}

/**
 * 获取历史轨迹
 */
async function obtainHistoricalTrajectory(imei: string, startTime: string, endTime: string, miningId:number){
  const { data } = await useGetTrackPosApi({
    imei,
    startTime,
    endTime,
    withStop: true,
    withPos: true,
    withTrip: true,
    withAlarm: true
  })
  if(isReplay.value){
    trackRef.value.restResources()
    trackRef.value.initData({
      imei,
      trajectoryData: data,
      miningId
    })
  }else{
    trajectoryRef.value.restResources()
    trajectoryRef.value.initData({
      trajectoryData: data,
      miningId
    })
  }
}

function tabChange(val) {
  switch (val) {
    case 'second':
      freightRef.value.init(dataInfo.value.otherInfo)
      break
  }
}

function handleClose() {
  activeName.value = 'first'

  const channelNames = jt1078AvsetAnalysis(deviceInfo.value?.jt1078Avch, deviceInfo.value?.jt1078Avset)
  if (channelNames.length === 0) {
    return
  }
  for (let i = 0; i < channelNames.length; i++) {
    let cl = channelNames[i]
    if (dataInfo.value.status) {
      if (dataInfo.value.status < 6) {
        avControl(dataInfo.value.imei, cl.channel).then((res) => {})
      } else {
        // 6已完成
        historyAvControl({
          imei: dataInfo.value.imei,
          channel: cl.channel,
          playbackMode: 2,
          playbackSpeed: 0,
          playbackTime: '2024-01-01 00:00:00'
        }).then((res) => {})
      }
    }
  }
}

</script>

<template>
  <el-card body-class="max_height" v-loading="loading">
    <div class="content">
      <div class="info">
        <ma-org-select v-model="queryForm.deptId" placeholder="请选择" authority @change="getWaybillList"></ma-org-select>
        <el-select v-model="currenWaybill" class="margin-tb" @change="waybillChange">
          <el-option v-for="item in waybillList" :key="item.id" :label="item.planningTime" :value="item.id">
            <span>{{ item.planningTime }}</span>
            <span style="float: right">{{ item.status }}</span>
          </el-option>
        </el-select>
        <el-descriptions v-show="currenWaybill" :column="1">
          <el-descriptions-item label="运单状态">
            <ma-dict-label dict-type="waybill_state" :dict-value="dataInfo?.status" />
          </el-descriptions-item>
          <el-descriptions-item label="车辆车牌号">{{ dataInfo?.plateNo }}</el-descriptions-item>
          <el-descriptions-item label="司机姓名">{{ dataInfo?.driverName }}</el-descriptions-item>
          <el-descriptions-item label="装货站点">{{ dataInfo?.mineName }}</el-descriptions-item>
          <el-descriptions-item label="计划拉运时间">{{ dataInfo?.planningTime }}</el-descriptions-item>
          <el-descriptions-item label="开始拉运时间">{{ dataInfo?.startTime }}</el-descriptions-item>
          <el-descriptions-item label="结束拉运时间">{{ dataInfo?.endTime }}</el-descriptions-item>
          <el-descriptions-item label="货源名称">{{ dataInfo?.sourceName }}</el-descriptions-item>
          <el-descriptions-item label="货源类型">{{ dataInfo?.sourceType }}</el-descriptions-item>
          <el-descriptions-item label="货物类型">{{ dataInfo?.goodsType }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <div class="right">
        <div class="top">
          <div v-show="isReplay" style="display: flex">
            <div class="camera" style="flex: 2">
              <div v-for="(num, i) in 4" :key="num" class="camera_item">
                <VuePlayer :ref="(el) => (realTimeVideoRefs[i] = el)" :keys="num"></VuePlayer>
              </div>
            </div>
            <div style="flex: 1">
              <CdlMap ref="trackRef" v-model:model-value="trackModel" enclosure HistoricalTrajectory realTimeLocation></CdlMap>
            </div>
          </div>
          <div v-show="!isReplay"  style="display: flex">
            <div style="flex: 2">
              <div style="height: 100%; width: 100%; background-color: #0a0a0a">
                <VuePlayer :ref="playbackVideoRef"></VuePlayer>
              </div>
            </div>
            <div style="flex: 1">
              <CdlMap ref="trajectoryRef" v-model:model-value="trajectoryModel" enclosure HistoricalTrajectory></CdlMap>
            </div>
          </div>
        </div>
        <div class="bottom">
          <el-tabs v-model="activeName" style="height: 100%; width: 100%" @tabChange="tabChange">
            <el-tab-pane label="报警信息" name="first">
              <el-table :data="alarmData">
                <ma-dict-column prop="type" label="报警状态" dict-type="alarm_type"></ma-dict-column>
                <el-table-column label="报警开始时间" prop="occurTime"></el-table-column>
                <el-table-column label="报警结束时间" prop="endTime"></el-table-column>
                <el-table-column label="报警等级" prop="level"></el-table-column>
                <el-table-column label="状态">
                  <template v-slot="scope">{{ scope.row.processStatus ? '已处理' : '未处理' }}</template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="装卸货时长" name="second">
              <FreightTimeCount ref="freightRef"></FreightTimeCount>
            </el-tab-pane>
            <el-tab-pane label="视频回放" name="third"> </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>
  </el-card>
</template>

<style scoped>
.content {
  display: flex;
  height: 100%;
}
.camera_item {
  box-sizing: border-box;
  background-color: black;
  border: 1px solid;
  width: 50%;
}
.content > .right {
  flex: 1;
  height: 100%;
}
.info {
  max-width: 350px;
  min-width: 300px;
  margin-right: 15px;
}
.right {
  display: flex;
  flex-direction: column;
}
.top {
  display: flex;
  height: 60%;
}
.bottom {
  height: 40%;
}
.top > div {
  flex: 1;
}
.camera {
  display: flex;
  flex-wrap: wrap;
  height: 100%;
}
.camera > div {
  width: 50%;
  height: 50%;
}
.channel {
  display: flex;
}
.channel > div {
  flex: 1;
}
.margin-tb {
  margin: 15px 0;
}
>>> .max_height {
  height: calc(100vh - 105px - var(--theme-header-height));
}
</style>
